package signup.domain;

import java.sql.Date;
import java.sql.Time;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class EventService {
	
	
	
	static Event createEvent(String Name, String Description, Date StartDate, Time StartTime,
			Date EndDate, Time EndTime, Users Coordinator)
	{
		EntityManagerFactory emf =
	        Persistence.createEntityManagerFactory("pu");
		EntityManager jpa = emf.createEntityManager();
		
        EntityTransaction tx = jpa.getTransaction();
        try {
            tx.begin();
            if(Coordinator!=null)
            {
            Coordinator=jpa.merge(Coordinator);
            }
            Event u=new Event("Wedding","Wedding",StartDate,StartTime,EndTime,EndDate, Coordinator);
    		
            jpa.persist(u);
            tx.commit();
            return u;
        } catch (Exception x) {
        	x.printStackTrace();
        	tx.rollback();
        	return null;
            
        }
        
        
	
	}
	
	static public Event addPosition(Event e, Position p){
		
		EntityManagerFactory emf =
	        Persistence.createEntityManagerFactory("pu");
		EntityManager jpa = emf.createEntityManager();
		
        EntityTransaction tx = jpa.getTransaction();
        try {
            tx.begin();
            e=jpa.merge(e);
            if(p!=null)
            {
            	p=jpa.merge(p);
            }
            e.addPosition(p);
            
            jpa.persist(e);
            
            tx.commit();
            
        } catch (Exception x) {
        	x.printStackTrace();
        	tx.rollback();
        	return null;
            
        }
        
		return e;
	}
	
	static Event update(Event event)
	{
		EntityManagerFactory emf =
	        Persistence.createEntityManagerFactory("pu");
		EntityManager jpa = emf.createEntityManager();
		
        EntityTransaction tx = jpa.getTransaction();
        try {
            tx.begin();
            event=jpa.merge(event);
            jpa.persist(event);
            tx.commit();
            
        } catch (Exception x) {
        	x.printStackTrace();
        	tx.rollback();
        	return null;
            
        }
		return event;
	}
	
	static Boolean delete(Event event)
	{
		EntityManagerFactory emf =
	        Persistence.createEntityManagerFactory("pu");
		EntityManager jpa = emf.createEntityManager();
		
        EntityTransaction tx = jpa.getTransaction();
        try {
            tx.begin();
            event=jpa.merge(event);
            jpa.remove(event);
            tx.commit();
            return true;
            
        } catch (Exception x) {
        	x.printStackTrace();
        	tx.rollback();
        	return false;
            
        }
		
	}
}
